#ifndef __RTMP_READER_H__
#define __RTMP_READER_H__

#ifdef __cplusplus
extern "C" {
#endif
    
#include "mlog.h"
#include "utils.h"
#include "srs_librtmp.h"
#include <pthread.h>

#define ERR_RTMP_ERROR			-100
#define ERR_RTMP_CLOSED			-101
#define ERR_RTMP_TIMEOUT		-1011

#define payload_freep(p)		if (p) { delete[] (p); p = NULL; }

typedef void (*packet_handler)(char* data, int size, void* param);

class CRtmpReader
{
public:
	CRtmpReader();
	~CRtmpReader();
	
public:
	int open(const char* serverip, const char* id, int channel, int sndtimeout = 2000, int rcvtimeout = 6000);
	void close(int seconds = 0);
	void setPacketHandler(packet_handler handler, void* param) { mPacketHandler = handler; mPacketHandlerParam = param; }
	int swapStream(const char* stream_name);
	int saveStream(const char* stream_name, const char* serial_no);
	int pauseStream(int pause);
	bool isConnected();
	void getReceivedInfo(int* rcvbytes, int* rcvpkts);
	
private:
	enum STATE {
		STAT_IDLE = 0, 
		STAT_RTMP_OPEN, STAT_RTMP_CLOSE, STAT_RTMP_RECEIVE, STAT_RTMP_PAUSE, STAT_RTMP_PAUSE_WAIT,
		STAT_ERROR,
	};

private:
	int mState;
	int64_t mWaitTime;
	
	srs_rtmp_t mHandle;
	packet_handler mPacketHandler;
	void* mPacketHandlerParam;
	
	int mRecvBytes;
	int mRecvPackets;
	int64_t mLastRecvTime;
	
	char mServer[64];
	char mID[64];
	int mChannel;
	int mSndTimeout;
	int mRcvTimeout;
	
	pthread_t mThread;
	bool mIsRunning;
	
private:
	static void* thread_func(void* p) { ((CRtmpReader*)p)->onThread(); return NULL; }
	void onThread();
	
	void rtmpClose();
	srs_rtmp_t rtmpOpen();
	void rtmpReceive();
};
    
#ifdef __cplusplus
}
#endif
    
#endif
